<template>

  <view  @longtap.stop="handleRemove(item, index)" @tap.stop="reply(item, index)"  class="comment" :style="{paddingLeft: level=== 2 ? '64rpx' : '0'}"
        v-for="(item, index) in childCommentList " :key="index">
    <view :id="item.id" :class="['comment', { 'is-focused': item.id == focusId  }]" style="background-color: rgb(245, 245, 245)">
      <view class="top">
        <view class="left" :style="{width: level !== 1 ? 'calc(100% - 64rpx)' : '100%'}">
          <view @tap.stop="toUserInfo(item.userId)" class="heart-photo">
            <image style="position:relative;"
                   :class="level !== 1 ? 'child-avatar' : 'avatar'"
                   :src="item.avatar" mode=""></image>
          </view>
          <view class="user-info">
            <view style="display: flex;align-items: center;justify-content: space-between">
              <view style="display: flex;align-items: center">
                <view @tap.stop="toUserInfo(item.userId)" class="name u-line-1">{{ item.username }}</view>
                <view style="display: flex;align-items: center">
                  &nbsp;<view v-show="level > 1">
                  <u-icon color="rgb(150,150,150)" name="play-right-fill"></u-icon>
                </view>&nbsp;
                  <view class="u-line-1" v-show="level > 1" style=" font-size: 28rpx;color:rgb(150,150,150);">
                    {{ parentName }}
                  </view>
                </view>
              </view>
              <view class="right" :class="{ highlight: item.isLike }">
                <view class="num">{{ item.liked }}&nbsp;</view>
                <image v-if="!item.isLiked" class="like-image" src="https://www.douluodalu.icu:9000/school/static/like.png"
                       @tap.stop="getLike(index)"></image>
                <image v-if="item.isLiked" class="like-image"
                       src="https://www.douluodalu.icu:9000/school/static/like_active.png"
                       @tap.stop="getLike(index)"></image>
              </view>
            </view>
            <view class="content">{{ item.content }}</view>
            <u-grid :border="false" v-if="item.fileList">
              <u-grid-item v-for="(media,fileIndex) in item.fileList"
                           :key="fileIndex"
                           @tap.stop="sendFileList(fileIndex,item.fileList,item)">
                <navigator url="/pages/index/commentFullScreen" animation-type="">

                  <image v-if="isImageUrl(media)"
                         :class="level === 1 ? 'file-item-multi' : 'file-item-multi-child'"
                         lazy-load
                         :src="media">
                    <template v-slot:loading>
                      <up-loading-icon></up-loading-icon>
                    </template>
                    <template #error>
                      <view style="font-size: 24rpx;">加载失败</view>
                    </template>
                  </image>
                  <video v-if="isVideoUrl(media)"
                         object-fit="cover"
                         style="position: relative;"
                         :enable-progress-gesture="false"
                         :vslide-gesture-in-fullscreen="false"
                         :show-fullscreen-btn="false"
                         :show-center-play-btn="false"
                         :show-play-btn="false"
                         :class="level === 1 ? 'file-item-multi' : 'file-item-multi-child'"
                         :src="item.fileList">
                    <cover-image
                        class="play-btn"
                        src="https://www.douluodalu.icu:9000/school/static/play_white.png">
                    </cover-image>
                  </video>
                </navigator>

              </u-grid-item>
            </u-grid>

            <view class="date">
              {{ formatTimeAgo(item.publishTime) }}
              {{ formatLocation(item.location) }}
              <view @tap="reply(item,index)" class="reply">回复</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <ChildComment v-if="item.child != undefined"
                  :level="level + 1"
                  @handleRemove.stop="handleRemove"
                  :focusedCommentId="focusedCommentId"
                  :parentName="item.username"
                  :ancestorId="ancestorId"
                  :parentId="item.parentId"
                  :childCommentList="item.child"/>
    <view v-if="level === 1 &&
    index+1 == childCommentList.length"
          style="height: 50px"></view>
  </view>
</template>
<script>
import ChildComment from "@/components/comment/childComment.vue";
import {addComment, likeComment, selectSchoolCommentById} from "@/api/comment";
import {getToken, getUserId} from "@/utils/auth";

export default {
  name: 'childComment',
  components: {ChildComment},
  props: ['childCommentList', 'parentId', 'level', 'parentName', 'focusedCommentId','ancestorId'],
  data() {
    return {
      scrollTop: 0,
      childLevel:0,
      removing:false,
      sendTrigger: 'comment',
      focusShow: false,
      textareaWidth: 60,
      textareaFocus: false,
      showEmptyComent: false,
      tempComment: [],
      maxHeight: '20px',
      maxLines: 4,
      showReplyPopup: false,
      //键盘高度
      keyboardHeight: 0,
      keyboardHeight1: 0,
      bottomList: [
        // {
        //   url: 'https://www.douluodalu.icu:9000/school/static/voice.png',
        //   type: 1
        // },
        {
          url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
          type: 2
        }
      ],
      bottomList2: [{
        url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
        type: 1
      },
        //   {
        //   url: 'https://www.douluodalu.icu:9000/school/static/voice.png',
        //   type: 3
        // }, {
        //   url: 'https://www.douluodalu.icu:9000/school/static/post_emoj.png',
        //   type: 4
        // }, {
        //   url: 'https://www.douluodalu.icu:9000/school/static/aite.png',
        //   type: 5
        // }
      ],
      // 聊天框距离底部的高度
      bottomHeight: 0,
      childCommentIndex: null,
      childCommentInfo: [],
      commentForm: {
        content: '', // 内容
        images: '', // 图片
        videos: '', // 视频
        parentId: '',
        postId: '',
        rootCommentId: '',
      },
      show: false,
      loading: false,
      commentIndex: 0,
      current: 0,
      commentType: [
        {type: 1, name: "最热评论", url: "http://www.douluodalu.icu:9000/school/static/hot-comment.png"},
        {type: 2, name: '最新评论', url: 'http://www.douluodalu.icu:9000/school/static/new-comment.png'},
        {type: 3, name: '只看楼主', url: 'http://www.douluodalu.icu:9000/school/static/only-comment.png'},
        {type: 4, name: '有视频', url: 'http://www.douluodalu.icu:9000/school/static/video-comment.png'}
      ],
      channelInfo: {},
      focusId: '',
      commentList: [],
      postInfo: {},
      searchParams: {
        hot: true,
        latest: false,
        onlyOwner: false,
        haveVideo: false,
        pageSize: 15,
        current: 1,
        postId: ''
      }
    };
  },
  mounted() {
    this.focusId = this.focusedCommentId
    setTimeout(() => {
      this.focusId  = ''
    }, 2500)
    if(this?.focusedCommentId != undefined && this?.focusedCommentId != '' && this?.focusedCommentId != ''){
      this.toNoticeComment(this.focusedCommentId,this.commentList)
    }
    // 获取目标组件的位置信息




    if (this.childCommentList != null) {
      this.childCommentList.forEach(item => {
        item.fileList = []
        if (item.images != undefined && item.images != null) {
          let imagesList = item.images.split(',');
          item.fileList = [...item.fileList, ...imagesList]
        }
        if (item.videos != undefined && item.videos != null) {
          let videosList = item.videos.split(',');
          item.fileList = [...item.fileList, ...videosList]
        }
      })
    }
  },
  methods: {
    toNoticeComment(id, commentArray) {
      for (let i = 0; i < commentArray.length; i++) {
        if (commentArray[i].id === id) {
            this.$nextTick(() => {
              const query = uni.createSelectorQuery().in(this);
              console.log(this.focusId)
              query.select(`.top`).boundingClientRect((data) => {
                console.log("得到布局位置信息" + JSON.stringify(data));
                console.log("节点离页面顶部的距离为" + data.top);
                uni.pageScrollTo({
                  scrollTop: data.top -80 -  data.height,
                  duration: 100
                });
                setTimeout(() => {
                  this.focusId = ''
                }, 2500)
                // 调用 uni.pageScrollTo 进行页面滚动
              }).exec();
            })
          return;
        } else if (Array.isArray(commentArray[i].child)) {
          this.toNoticeComment(id, commentArray[i].child);
        }
      }
    },
    handleRemove(item,index){
      this.removing = true
      if(item.userId == getUserId()){
        this.$emit('handleRemove', item,index,this.ancestorId)
      }
      this.removing = false

    },
    toUserInfo(userId) {
      uni.navigateTo({
        url: '/pages/my/userInfo?id=' + userId
      })
    },
    async getLike(index) {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      } else {
        const res = await likeComment(this.childCommentList[index].id)
        this.childCommentList[index].isLiked = !this.childCommentList[index].isLiked;
        if (this.childCommentList[index].isLiked) {
          this.childCommentList[index].liked++;
        } else {
          this.childCommentList[index].liked--;
        }
      }

    },
    sendFileList(fileIndex, fileList, item) {
      setTimeout(() => {
        uni.$emit('sendFileList', {
          post: item,
          fileList: fileList,
          currentIndex: fileIndex
        })
      }, 500)

    },
    isImageUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tif', '.tiff'];
      // console.log(url+'----后缀：'+ extension +'----->  '+imageExtensions.includes(extension))
      return imageExtensions.includes(extension);
    },
    // 新增图片
    isVideoUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      let videoExtensions = [".3gp", ".avi", ".flv", ".mkv", ".mov", ".mpg", ".mp4", ".rmvb", ".wmv"];
      // console.log(url+'----后缀：'+ extension +'----->  '+imageExtensions.includes(extension))
      return videoExtensions.includes(extension) && url.startsWith("http");
    },
    send(trigger) {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if (trigger == 'comment') {
        this.sendComment()
      } else {
        this.sendCommentReply()
      }
    },
    async sendComment() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if (this.commentForm.content.trim() == '' || this.commentForm.content.trim().length == 0) {
        uni.showToast({
          title: '你还没有输入评论',
          icon: 'none'
        })
        return
      }
      this.commentForm.postId = this.comment.postId
      this.commentForm.parentId = this.comment.id
      this.commentForm.rootCommentId = this.comment.id
      const res = await addComment(this.commentForm)
      if (res.code == 200 && res.data?.id !== undefined) {
        uni.pageScrollTo({
          scrollTop: 0, // 设置滚动到顶部的位置
          duration: 100 // 滚动动画时长，单位 ms
        });
        if (this.showEmptyComent && this.commentList.child == undefined && this.childCommentIndex == null) {
          let child = new Array(res.data)
          this.commentList.push(child)
        }
        if (!this.showEmptyComent && this.commentList.child != undefined && this.childCommentIndex == null) {
          this.commentList.child = [res.data, ...this.commentList.child]
        }
        this.showEmptyComent = false
        await this.getComment()
      } else {
        uni.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }

      this.scrollTop = this.scrollTop === 0 ? -1 : 0;
      this.commentForm.content = ''
      this.commentForm.videos = ''
      this.commentForm.images = ''
      this.commentForm.parentId = ''
      this.commentForm.rootCommentId = ''
      this.commentForm.postId = ''

    },
    async sendCommentReply() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if (this.commentForm.content.trim() == '' || this.commentForm.content.trim().length == 0) {
        uni.showToast({
          title: '你还没有输入评论',
          icon: 'none'
        })
        return
      }
      this.commentForm.postId = this.comment.postId
      const res = await addComment(this.commentForm)
      if (res.code == 200 && res.data?.id !== undefined) {
        uni.pageScrollTo({
          scrollTop: 0, // 设置滚动到顶部的位置
          duration: 100 // 滚动动画时长，单位 ms
        });
      } else {
        uni.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }


      this.scrollTop = this.scrollTop === 0 ? -1 : 0;
      this.commentForm.content = ''
      this.commentForm.videos = ''
      this.commentForm.images = ''
      this.commentForm.parentId = ''
      this.commentForm.rootCommentId = ''
      this.commentForm.postId = ''
      this.showEmptyComent = false
      this.sendTrigger = 'comment'
    },
    reply(comment, index) {
      this.$parent.reply(comment, index)

    },
    async getComment() {
      this.searchParams.postId = this.comment.id
      const {data: res} = await selectSchoolCommentById(this.comment.id);
      this.commentList = res[0];

      if (this.commentList.child == null || this.commentList.child == [] || this.commentList.child == undefined) {
        this.showEmptyComent = true
      }
    },
    onTextareaInput() {
      // 在这里可以处理行数
    },
    getKeyboardHeight(event) {
      this.keyboardHeight = event.detail.height
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      this.focusShow = true
      this.textareaWidth = 80
    },
    removeKeyboardHeight(event) {
      // 在这里可以处理键盘高度
      this.textareaPlaceholder = `回复 ${this.comment.username} :`,
          this.textareaFocus = false
      this.keyboardHeight = 0
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      this.focusShow = false
      this.textareaWidth = 60
    },
    // 点赞
    formatTimeAgo(originalTimestamp) {
      const now = new Date();
      const timestampPlus8Hours = new Date(originalTimestamp);
      timestampPlus8Hours.setHours(timestampPlus8Hours.getHours() + 8);

      const timeDifference = now - timestampPlus8Hours;
      const seconds = Math.floor(timeDifference / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      const padZero = (num) => (num < 10 ? `0${num}` : num);

      if (days < 365) {
        if (days == 0) {
          if (hours >= 12) {
            return `${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
          } else if (hours > 0 && hours <= 12) {
            return `${hours}小时前`;
          } else if (minutes >= 1) {
            return `${minutes}分钟前`;
          } else {
            return '刚刚';
          }
        } else if (days == 1) {
          return `昨天 ${timestampPlus8Hours.getHours()}:${('0' + timestampPlus8Hours.getMinutes()).slice(-2)}`;
        } else {
          return `${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
        }
      } else {
        return `${timestampPlus8Hours.getUTCFullYear()}/${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
      }
    },
    formatLocation(location) {
      if (location == null) {
        return '未知';
      }
      location = location.replace(/省|市/g, '');

      return location;
    },
    // 回复列表
    getReply() {
    },
    notifyChoose(index) {
      this.commentIndex = index
      this.show = false
    },
    open() {
    },
    close() {
      this.show = false
    },
  }
};
</script>

<style lang="scss" scoped>
.like-image {
  height: 20px;
  width: 20px;
}

.avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: #f2f2f2;
}

.child-avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background-color: #f2f2f2;
}

.comment {
  padding: 30rpx 30rpx 0 30rpx;
  font-size: 30rpx;
  background-color: #ffffff;

  .top {
    display: flex;
    justify-content: space-between;
    padding-right: 60rpx;
  }

  .left {
    display: flex;
    width: 100%;

    .heart-photo {

    }

    .user-info {
      width: inherit;
      margin-left: 10rpx;

      .name {
        color: $u-light-color;
        font-size: 28rpx;
        margin-bottom: 4rpx;
      }

      .date {
        font-size: 20rpx;
        color: $u-light-color;
        display: flex;
        align-items: center;
      }

      .reply {
        font-size: 20rpx;
        color: #9a9a9a;
        background-color: rgba(154, 154, 154, 0.14);
        border: none;
        padding: 2px 5px;
        border-radius: 5px;
        margin-left: 10rpx;
      }
    }
  }

  .right {
    display: flex;
    font-size: 20rpx;
    align-items: center;
    color: #9a9a9a;

    .like {
      margin-left: 6rpx;
    }

    .num {
      font-size: 26rpx;
      color: #9a9a9a;
    }
  }

  .highlight {
    color: #5677fc;

    .num {
      color: #5677fc;
    }
  }
}


.item {
  background-color: rgb(245, 245, 245);
  width: 100%;
}

.comment {
  background-color: rgb(245, 245, 245);
  width: 100%;
}

.comment.is-focused {
  animation: blink 1s linear infinite;
}

@keyframes blink {
  0% {
    background-color: transparent;
  }
  50% {
    background-color: rgba(78, 164, 249, 0.16);
  }
  100% {
    background-color: transparent;
  }
}

.file-item-multi {
  //margin-bottom: 0.5rem;
  border-radius: 5px;
  width: 6.7rem;
  height: 6.7rem;
  position: relative;
}

.file-item-multi-child {
  border-radius: 5px;
  width: 6.2rem;
  height: 6.2rem;
  position: relative;
}

.play-btn {
  width: 30px;
  height: 30px;
  top: 35%;
  left: 35%;
  position: absolute
}

#bottom-list {
  display: flex;
  flex-direction: column;
  padding: 10px 0;
  bottom: 0;
  z-index: 999;
  width: 100vw;
  position: fixed;
  background-color: #FFFFFF;
  //max-height: 12vh;
}

textarea {
  background-color: rgba(154, 154, 154, 0.15);
  border-radius: 60rpx;
  padding: 8px;
  max-height: 12vh;
}

.bottom-media-list {
  display: flex;
  align-items: center;
  margin: 0 30rpx;
  width: max-content;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  box-shadow: 0 0 10px 0px #b7b4b4;
}

.bottom-media-list-item {
  padding: 5px;
}

.bottom-media-list-item-image {
  width: 128rpx;
  height: 128rpx;
  z-index: 99
}

.close-images {
  z-index: 999;
  position: relative;
  left: 3.9rem;
  top: -5.0rem;
  background-color: white;
  border-radius: 50%;
  width: max-content;
  height: max-content;
}

.textarea-model-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 30rpx;

}
</style>
